package com.dl.helloworld;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.util.Log;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

public class BaseActivity extends AppCompatActivity {

    private ForceOfflineReceiver receiver;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState, @Nullable PersistableBundle persistentState) {
        super.onCreate(savedInstanceState, persistentState);
        Log.d("BaseActivity", getClass().getSimpleName());
    }


    @SuppressLint("UnspecifiedRegisterReceiverFlag")
    @Override
    protected void onResume() {
        super.onResume();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("com.dl.helloworld.FORCE_OFFLINE");
        receiver = new ForceOfflineReceiver();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            getApplicationContext().registerReceiver(
                    receiver,
                    intentFilter,
                    Context.RECEIVER_NOT_EXPORTED);
        } else {
            registerReceiver(receiver, intentFilter);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (receiver != null) {
            try {
                // 根据注册时使用的 Context 注销接收器
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                    getApplicationContext().unregisterReceiver(receiver);
                } else {
                    unregisterReceiver(receiver);
                }
            } catch (IllegalArgumentException e) {
                // 防止极端情况下的重复注销
                e.printStackTrace();
            }
            receiver = null; // 置空避免野指针
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ActivityController.removeActivity(this);
    }


}
